﻿using Application.Users.Interfaces;
using MediatR;
using Shared.Http.APIResult;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Application.Users.Commands.DeleteUser
{
    public record DeleteUserCommand(IList<Guid> UserIds):IRequest<OperationResult<List<Guid>>>;
    public class DeleteUserCommandHandler : IRequestHandler<DeleteUserCommand, OperationResult<List<Guid>>>
    {
        private readonly IUserWriteRepository _repository;
        public DeleteUserCommandHandler(IUserWriteRepository repository)
        {
            _repository = repository;
        }

        public async Task<OperationResult<List<Guid>>> Handle(DeleteUserCommand request, CancellationToken cancellationToken)
        {
            OperationResult<List<Guid>> result = new()
            {
                Errors = [],
                Data = []
            };
            foreach (var item in request.UserIds)
            {
                try
                {
                    await _repository.DeleteAsync(item,cancellationToken);
                    result.Data.Add(item);
                }
                catch (Exception ex)
                {
                    result.Errors.Add(new()
                    {
                        Message = ex.Message,
                    });
                }
            }

            return result;
        }
    }
}
